<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <!-- <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="auto">
        <el-form-item prop="keywords" label="关键字">
          <el-input
            v-model="queryParams.keywords"
            placeholder="角色名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div> -->
    <el-card shadow="hover" class="data-table">
      <div class="data-table__toolbar">
        <div class="data-table__toolbar--actions">
          <el-button type="success" icon="plus" @click="handleOpenDialog">新增</el-button>
          <el-button
            v-if="isBatchDelete"
            type="danger"
            :disabled="selectedIds.length === 0"
            icon="delete"
            @click="handleDelete"
          >
            删除
          </el-button>
        </div>
      </div>
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        class="data-table__content"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          v-for="(ruleColumn, index) in tableRuleColumns"
          :key="index"
          :label="ruleColumn.label"
          align="left"
          :sortable="ruleColumn.sortable"
          :filters="ruleColumn.filters"
          :filter-method="ruleColumn.filterMethod"
        >
          <template #default="{ row }">
            <span>{{ formatCellValue(row, ruleColumn) }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-if="isDownload"
              type="primary"
              size="small"
              link
              icon="download"
              @click="() => handleDownload(scope.row.id)"
            >
              下载
            </el-button>
            <el-button
              v-if="isBatchDelete"
              type="danger"
              size="small"
              link
              icon="delete"
              @click="() => handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <offset-pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:offset="queryParams.offset"
        v-model:limit="queryParams.limit"
        @pagination="fetchData"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
// import { ref, reactive, computed, onMounted } from "vue";
import { useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import type { CommonHmiDataOffsetPageQuery } from "@/api/hmi/common-hmi-data.api";
import type { ColumnRule, TableHeaderRule } from "@/types/hmi-data-table";
import { formatBatchDeleteTableData, formatCellValue } from "@/utils/hmi-data-table";
import { DeviceEnum } from "@/enums/settings/device.enum";
import { useAppStore, useCommonApiStore, useHmiConfigStore } from "@/store";

defineOptions({
  name: "BatchDelete",
  inheritAttrs: false,
});

const route = useRoute();
const appStore = useAppStore();
const commonApiStore = useCommonApiStore();
const hmiConfigStore = useHmiConfigStore();

const loading = ref(false);
const selectedIds = ref<number[]>([]);
const isBatchDelete = ref(false);
const isDownload = ref(false);
const apiPath = ref<string>("");
// const apiPath = computed(() => {
//   // 兼容 meta.params.api 可能为字符串或对象
//   const metaApi = route?.meta?.params?.api;
//   if (typeof metaApi === "string") return metaApi;
//   if (metaApi && typeof metaApi === "object" && "value" in metaApi) return metaApi.value;
//   return "";
// });
const total = ref(0);

const queryParams = reactive<CommonHmiDataOffsetPageQuery>({
  offset: 0,
  limit: 10,
  keywords: "",
  createTime: ["", ""],
});

const tableHeaders = ref<any[]>([]);
const tableData = ref<any[]>([]);

const tableRuleColumns = ref<ColumnRule[]>([]);
const curTableRule = ref<TableHeaderRule | null>(null);

// 获取数据
async function fetchData() {
  loading.value = true;
  try {
    const ret_api_data = await commonApiStore.fetchList(apiPath.value, { ...queryParams });
    total.value = +ret_api_data.total;
    const { tableHeaders: newTableHeaders, tableData: newTableData } = formatBatchDeleteTableData(
      ret_api_data.list,
      tableRuleColumns.value
    );
    tableHeaders.value = newTableHeaders;
    tableData.value = newTableData;
  } catch (error) {
    ElMessage.error("获取数据失败");
    // 控制台详细错误
    console.error("获取数据失败", error);
  } finally {
    loading.value = false;
  }
}

// 查询（重置页码后获取数据）
function handleQuery() {
  queryParams.offset = 0;
  fetchData();
}

// 重置查询
function handleResetQuery() {
  queryParams.offset = 0;
  queryParams.keywords = "";
  queryParams.createTime = ["", ""];
  fetchData();
}

// 下载行数据到一个表格
function handleDownload(rowId: number) {
  // TODO: 实现下载逻辑
  ElMessage.info(`下载功能开发中，行ID: ${rowId}`);
}

// 行复选框选中
function handleSelectionChange(selection: any[]) {
  selectedIds.value = selection.map((item: any) => item.id);
}

// 删除行数据
function handleDelete(rowId?: number) {
  const rowIds = rowId ? [rowId] : selectedIds.value;
  if (!rowIds.length) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      loading.value = true;
      try {
        await commonApiStore.batchDelete(apiPath.value, rowIds);
        ElMessage.success("删除成功");
        handleResetQuery();
      } catch (error) {
        ElMessage.error("删除失败");
        console.error("删除失败", error);
      } finally {
        loading.value = false;
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
}

function handleOpenDialog() {
  // TODO: 实现新增弹窗逻辑
  ElMessage.info("新增功能开发中");
}

function updateTableRuleAndFetchData(api: string) {
  // const headerRule = hmiConfigStore.getTableHeaderRuleByUri(api);
  const headerRule = hmiConfigStore.getTableHeaderRuleByPath(route.path);
  if (headerRule) {
    curTableRule.value = headerRule;
    tableRuleColumns.value =
      headerRule.columns?.slice().sort((a, b) => (a.index ?? 0) - (b.index ?? 0)) || [];
  } else {
    curTableRule.value = null;
    tableRuleColumns.value = [];
  }
  fetchData();
  isBatchDelete.value = !!curTableRule.value?.isBatchDelete;
  isDownload.value = !!curTableRule.value?.isDownload;
}

onMounted(async () => {
  try {
    apiPath.value = route?.meta?.params?.api || "";
    await hmiConfigStore.initHmiConfig();
    if (apiPath.value) {
      updateTableRuleAndFetchData(apiPath.value);
    }
  } catch (error) {
    console.error("初始化配置失败:", error);
  }
});

// apiPath 根据 route?.meta?.params?.api; 计算得到
// 监听 apiPath 变化，只有当前页面激活时，才执行 updateTableRuleAndFetchData 函数，进行更新
const isPageActive = ref(true); // 添加页面激活状态标识

onActivated(() => {
  isPageActive.value = true;
});

onDeactivated(() => {
  isPageActive.value = false;
});

// 监听 API 变化
// 只有
watch(
  () => apiPath.value,
  (oldApi, newApi) => {
    console.log(
      "batch-delete oldApi",
      oldApi,
      "newApi",
      newApi,
      "isPageActive",
      isPageActive.value
    );
    if (newApi && isPageActive.value) {
      console.log("batch-delete updateTableRuleAndFetchData", newApi);
      updateTableRuleAndFetchData(newApi);
    }
  }
  // { immediate: true }
);
</script>

<style lang="scss"></style>
